import psutil
import asyncio
import logging
from loguru import logger
from datetime import datetime
from playwright import async_api
from apscheduler.schedulers.asyncio import AsyncIOScheduler


def sync_job():
    logger.info('执行同步任务')


async def async_job():
    logger.info('开始执行异步任务')
    await asyncio.sleep(1)
    logger.info('异步任务执行完成')


async def open_web(i: int):
    logger.info(f"open web: {i}")
    
    async with async_api.async_playwright() as p:
        browser = await p.chromium.launch(
            headless=True
        )
        context = await browser.new_context()
        page = await context.new_page()
        await page.goto("https://www.baidu.com")
        await page.wait_for_timeout(1 * 1000)
        await page.get_by_role("link", name="登录").click()
        await page.wait_for_timeout(1 * 1000)
        await page.wait_for_selector("xpath=//a[contains(@id, 'closeBtn')]", timeout=30 * 1000)
        await page.locator("xpath=//a[contains(@id, 'closeBtn')]").click()
        await page.wait_for_timeout(1 * 1000)
    
    logger.info(f"close web: {i}")


async def test():
    for i in range(10):
        await open_web(i=i)


# 添加资源监控函数
async def monitor_resources():
    """监控系统资源使用情况"""
    # 获取当前进程资源使用情况
    process = psutil.Process()
    mem_info = process.memory_info()
    cpu_percent = process.cpu_percent(interval=1)
    
    # 获取系统资源使用情况
    system_cpu = psutil.cpu_percent(interval=0.1)
    system_mem = psutil.virtual_memory().percent
    
    logger.info(f"资源监控 - 进程CPU: {cpu_percent}%, 进程内存: {mem_info.rss / 1024 / 1024:.2f}MB, 系统CPU: {system_cpu}%, 系统内存: {system_mem}%")


# 添加获取僵尸进程数量的函数
def get_zombie_process_count():
    """获取当前系统中的僵尸进程数量"""
    try:
        # 获取所有进程
        processes = psutil.process_iter(['status'])
        # 筛选状态为'zombie'的进程
        zombie_count = sum(1 for p in processes if p.info['status'] == psutil.STATUS_ZOMBIE)
        return zombie_count
    except Exception as e:
        logger.error(f"获取僵尸进程数量失败: {str(e)}")
        return -1

# 修改资源监控函数，添加僵尸进程监控
def monitor_zombies():
    """监控僵尸进程数量"""
    zombie_count = get_zombie_process_count()
    if zombie_count >= 0:
        logger.info(f"当前系统僵尸进程数量: {zombie_count}")
    else:
        logger.error("无法获取僵尸进程数量")


async def schedule():
    logging.basicConfig()
    logging.getLogger('apscheduler').setLevel(logging.WARNING)

    scheduler = AsyncIOScheduler(timezone='Asia/Shanghai')
    # scheduler.add_job(sync_job, 'interval', seconds=5, id='sync_job', next_run_time=datetime.now())
    # scheduler.add_job(async_job, 'interval', seconds=5, id='async_job', next_run_time=datetime.now())
    scheduler.add_job(test, 'interval', minutes=1, id='test', next_run_time=datetime.now())
    scheduler.add_job(monitor_resources, 'interval', seconds=10, id='monitor_resources', next_run_time=datetime.now())
    scheduler.add_job(monitor_zombies, 'interval', seconds=10, id='monitor_zombies', next_run_time=datetime.now())

    scheduler.start()

    try:
        while True:
            await asyncio.sleep(1)
    except KeyboardInterrupt:
        scheduler.shutdown()

if __name__ == "__main__":
    asyncio.run(schedule())
